<template>
    <div class="container" :class="isUpdate&&'fadeIn'">
        <div class="theme-1" v-if="templateStyle==='level-1'||templateStyle==='level-3'">
            <div class="container">
                <aside class="pit-words">
                    <div class="chinese-words" data-name="word-button" v-for="(item,index) in wordArr"
                         :class="activeIndex === index&&'active'"
                         @click="answerHandler(item,index,item.order)">
                        <em v-if="item.chinese">{{item.chinese}}</em>
                        <em v-else-if="item.english">{{item.english}}</em>
                        <em v-else-if="item.pinyin">{{item.pinyin}}</em>
                    </div>
                </aside>
                <h2 class="english">
                    <div class="question" v-for="(sen,index) in content.sentences"
                         v-html="getHtml(sen,index)" @click="clickFn($event)">
                    </div>
                </h2>

            </div>
        </div>
    </div>
</template>
<script>
    import Vue from 'vue';
    import {mapState, mapGetters, mapActions} from 'vuex'
    import Component from 'vue-class-component'
    import R from 'ramda';
    import loadingImage from '~/components/loadingImage'

    @Component({
        components: {loadingImage},
        async fetch({store, params}) {
            await store.dispatch("index/exercise/index/setContentInfo", params);
        },
        computed: {
            wordArr() {
                const wordArr = [];
                if (this.content.answers) {
                    for (let i = 0; i < this.content.answers.length; i++) {
                        wordArr.push(this.content.answers[i]);
                    }
                }
                return wordArr.sort(function () {
                    return Math.random() - 0.5
                });
            },
            ...mapState('index/exercise/index', {
                contentInfo: state => state.contentInfo,
                templateStyle: state => state.templateStyle,
                content: state => state.contentInfo ? state.contentInfo.content : {}
            }),
        },
        methods: {
            ...mapActions('index/exercise/index', [
                'setAnswer',
                'setMyAnswer'
            ]),
        },
        watch: {
            content() {
//                当数据发生变化后执行动画效果
                this.isUpdate = true;
                const initData = {
                    activeItem: null,
                    activeIndex: "",
                    answerArr: [],
                    errorMessage: "",
                    correctArr: [],
                    selectAnswer: []
                };
                const init = (val, key) => {
                    this[key] = val;
                };
                R.forEachObjIndexed(init)(initData);
                this.init();
                setTimeout(_ => {
                    this.isUpdate = false;
                }, 600)
            }
        },


    })
    export default class chooseAnswer extends Vue {
        activeItem = null;
        activeIndex = "";
        answerArr = [];
        isUpdate = false;
        errorMessage = "";
        correctArr = [];
        selectAnswer = [];

        created() {
            console.log(this.content)
        }

        mounted() {
            this.init();
        }

        answerHandler(item, index, order) {
            this.activeIndex = index;
            this.activeItem = item;
        }

        clickFn(e) {
            if (e.target.nodeName.toUpperCase() === "DIV" && e.target.className === "topic-pit-btn") {
                let ele = e.target;
                let eleIndex = ele.getAttribute("data-name");
                if (this.activeItem != null) {
                    if (this.answerArr[eleIndex] === "0") {
                        Vue.set(this.answerArr, eleIndex, this.activeItem);
                        Vue.set(this.selectAnswer, eleIndex, this.activeItem.english || this.activeItem.chinese);
                        this.wordArr.splice(this.activeIndex, 1);
                        this.activeItem = null;
                        this.activeIndex = null;
                    } else {
                        this.wordArr.splice(this.activeIndex, 1);
                        this.wordArr.push(this.answerArr[eleIndex]);
                        Vue.set(this.answerArr, eleIndex, this.activeItem);
                        Vue.set(this.selectAnswer, eleIndex, this.activeItem.english || this.activeItem.chinese);
                        this.activeItem = null;
                        this.activeIndex = null;
                    }
                } else {
                    if (this.answerArr[eleIndex] !== "0") {
                        this.wordArr.push(this.answerArr[eleIndex]);
                    }
                    Vue.set(this.answerArr, eleIndex, "0");
                    Vue.set(this.selectAnswer, eleIndex, "null");
                }
                this.setMyAnswer(this.selectAnswer.join(","));
                this.Answer(eleIndex);
            }
        }

        init() {
            this.$nextTick(_ => {
                const answerArr = this.content.answerOrder && this.content.answerOrder[0].split(",");
                const selectArr = [];
                if (answerArr) {
                    for (let i = 0; i < answerArr.length; i++) {
                        Vue.set(this.answerArr, i, "0");
                        Vue.set(this.correctArr, i, "0");
                        Vue.set(this.selectAnswer, i, "null");
                    }
                }
                if (this.content.answerSenteces) {
                    for (let i = 0; i < this.content.answerSenteces.length; i++) {
                        this.errorMessage += (this.content.answerSenteces[i].chinese || this.content.answerSenteces[i].english) + "<br>";
                    }
                } else if (answerArr) {
                    for (let i = 0; i < this.content.answers.length; i++) {
                        for (let j = 0; j < answerArr.length; j++) {
                            if (answerArr[j] === this.content.answers[i].order) {
                                Vue.set(selectArr, j, this.content.answers[i].chinese || this.content.answers[i].english);
                            }
                        }
                    }
                    for (let i = 0; i < selectArr.length; i++) {
                        this.errorMessage += (i + 1) + "." + selectArr[i] + "<br>";
                    }
                }
                this.setAnswer({
                    answer: false,
                    msg: this.errorMessage
                });
            })
        }

        Answer(Index) {
            let answer = false;
            if (this.answerArr[Index].order) {
                Vue.set(this.correctArr, Index, this.answerArr[Index].order);
            } else {
                Vue.set(this.correctArr, Index, "0");
            }
            for (let i = 0; i < this.content.answerOrder.length; i++) {
                if (this.correctArr.toString() === this.content.answerOrder[i]) {
                    answer = true;
                }
            }
            this.setAnswer({
                answer: answer,
                msg: this.errorMessage
            });
        }

        getHtml(item, index) {
            let obj = item;
            if (obj && obj.length) {
                const re = /([^\[\]]+)(?=\])/g;
                let arr = obj.match(re);
                if (arr) {
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i] % arr[i] === 0) {
                            let key = this.answerArr[arr[i] - 1] || '';
                            obj = obj.replace(/\[.]、?/, "<div class='topic-pit-btn' data-name='" + (arr[i] - 1) + "'>" + (key.chinese || key.english || '') + "</div>");
                        }
                    }
                }
                return obj;
            }
        }
    }
</script>
<style lang="scss">
    .theme-1 {
        .topic-pit-btn {
            width: 1.4rem;
            font-size: 22px;
            height: .5rem;
            vertical-align: middle;
            display: inline-block;
            border-radius: .2rem;
            box-shadow: -4px 4px 6px 2px #D63D0C inset, 2px -2px 6px #ffffff inset;
            background: #FB9A1E;
            text-align: center;
            line-height: .5rem;
            margin: 0 .1rem;
            cursor: pointer;
            color: black;

        }
    }
</style>
<style lang="scss" scoped>
    @import "~~assets/sass/mixins";

    .fadeIn {
        animation: fadeIn .4s ease-in;
        transform: translateZ(0);
    }

    @keyframes fadeIn {
        from {
            transform-origin: left;
            transform: scaleX(.4);
            opacity: 0;
        }
    }

    .theme-1 {
        text-align: center;
        color: white;
        .question {
            line-height: 1.9;
        }
        .container {
            text-align: left;
            margin-top: 50px;
            display: inline-block;
            min-height: 4rem;
            width: 700px;
            padding: 20px 70px;
            @include fullBgWithMainContentPicName("answer-bg.png");
            .answer {
                vertical-align: middle;
            }
            .english {
                margin: .3rem 0;
                font-size: 28px;

            }
            .chinese {
                margin: .3rem 0;
                font-size: 28px;
                .pit {
                    width: 1.4rem;
                    height: .5rem;
                    vertical-align: middle;
                    display: inline-block;
                    border-radius: .2rem;
                    box-shadow: -4px 4px 6px 2px #D63D0C inset, 2px -2px 6px #ffffff inset;
                    background: #FB9A1E;
                    margin: 0 .1rem;
                }
            }
            .pit-words {
                margin-top: .3rem;
                .chinese-words {
                    padding: .2rem .4rem;
                    box-sizing: border-box;
                    margin: 0 10px;
                    display: inline-block;
                    background: url("~~assets/img/main_content/exercise/content-button.png") no-repeat left top 4px;
                    background-size: 100% 100%;
                    border-radius: .3rem;
                    cursor: pointer;
                    color: black;
                    font-size: 22px;
                    &.active {
                        transition: all .1s ease-in;
                        background-image: url('~~assets/img/main_content/exercise/button-yellow-active.png');
                    }

                }
            }
        }
    }

</style>